<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\usersignin\api\controller;

use app\api\BaseController;
use app\api\model\User;
use app\api\model\Config;
use app\api\model\UserGroup;
use plugins\usersignin\api\model\UserSignin;
/**
 * 每日签到
 */
class User extends BaseController
{
    /**
     * 用户权鉴
     */
    public $middleware = [\app\api\middleware\AuthCheck::class];
    
    /**
     * 列表
     */
    public function index() 
    {
        if ($this->request->isPost()) {
            $input   = input('post.');
            $where[] = ['user_id', '=', $this->request->userId];
            $signin  = ! empty(UserSignin::where($where)->whereDay('create_time')->value('id'));
            $count   = UserSignin::where($where)->count();
            $data    = UserSignin::where($where)->order('create_time', 'desc')->page($input['page'], 15)->select();
            return json(['status'=>'success','message'=>'查询成功', 'data' => $data, 'count' => $count, 'signin' => $signin]);
        }
    }
    /**
     * 签到
     */
    public function signin()
    {
        if ($this->request->isPost()) {
            if (empty(UserSignin::where('user_id', $this->request->userId)->whereDay('create_time')->value('id'))) {
                $config = Config::getVal('app_usersignin');  
                if (! $config) {
                    $config = ['open' => 0];
                }
                if ($config['open'] != 1) {
                    return json(['status' => 'error','message' => '暂停每日签到活动']);
                }
                $integral = $config['integral'];
                $userInfo = User::were('id', $this->request->userId)->find();
                $userInfo->now_integral     = $userInfo->now_integral + $integral;
                $userInfo->history_integral = $userInfo->history_integral + $integral;
                $userInfo->save();
                // 插入记录
                UserSignin::create([
                    'user_id'     => $this->request->userId,
                    'integral'    => $integral,
                    'create_time' => date('Y-m-d H:i:s'),
                ]);
                return json(['status' => 'success', 'message' => '签到成功']);
            } else {
                return json(['status' => 'error','message' => '今日已签到']);
            }
        }
    }
}